package com.yxy.http;

import com.yxy.http.util.MD5Util;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@EnableAutoConfiguration
public class SampleController {

    private final Logger logger = LogManager.getLogger();

    @RequestMapping("/upload")
    public @ResponseBody
    void home(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String result = "error";
        Map<String, Object> map = new HashMap<String, Object>();
        String signFile = request.getHeader("signFile");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("接收开始时间：" + df.format(System.currentTimeMillis()));
        ServletContext servletContext = request.getSession().getServletContext();
        // 创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()
                .getServletContext());
        // 判断 request 是否有文件上传,即多部分请求
            if (multipartResolver.isMultipart(request)) {

            // 转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取文件
            MultipartFile file = multiRequest.getFile("file");
            //生成校验码
            String md5 = DigestUtils.md5Hex(file.getBytes());
            if(!StringUtils.equalsIgnoreCase(signFile,md5)){
                logger.info("校验失败");
                return;
            }
                // 取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 取得上传文件
                MultipartFile multipartFile = multiRequest.getFile(iter.next());
                if (multipartFile != null) {
                    // 拿到文件，存储
                    String originalFilename = multipartFile.getOriginalFilename();
                    System.out.println(originalFilename);
                    result = "success";
                }
            }
            logger.info("接收结束时间：" + df.format(System.currentTimeMillis()));
        }
    }

    @RequestMapping(value = "/download", method = {RequestMethod.POST}, produces = "application/json;charset=UTF-8")
    public @ResponseBody
    Object down(HttpServletResponse response) throws Exception {
        final Logger logger = LogManager.getLogger();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //从磁盘读取文件
        byte[] buffer = null;
        String md5ByFile = null;
        try {
            File file = new File("C:/chs-software/File/49.9.zip");
            InputStream is = new BufferedInputStream(new FileInputStream(file));
            buffer = new byte[is.available()];
            is.read(buffer);
            is.close();
            logger.info("生成32校验码开始："+ df.format(System.currentTimeMillis()));
            md5ByFile = MD5Util.getMd5ByFile(file);
            logger.info("生成32校验码结束：" +  df.format(System.currentTimeMillis()));
            System.out.println("生成32校验码"+md5ByFile);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        response.addHeader("sign", md5ByFile);
        return buffer;
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);

    }
}
